// page/cart/index.js

const { init } = require('./../../wxCloudClientSDK.umd.js')
// 指定云开发环境 ID
wx.cloud.init({
  env: "cloud1-9gel6ndh8e555155", // 当前的云开发环境 ID
});
    
const client = init(wx.cloud);

Page({
  data: {
    cartItems: [
      /*{
        id: 1,
        name: '超声波洁牙',
        specification: '标准洁牙服务',
        price: 299,
        quantity: 1,
        image: './images/innermirror.jpg',
        selected: true
      },
      {
        id: 2,
        name: '牙齿美白',
        specification: '冷光美白',
        price: 1980,
        quantity: 1,
        image: './images/innermirror.jpg',
        selected: true
      }*/
    ],
    recommendItems: [
      {
        id: 3,
        name: '儿童窝沟封闭',
        price: 180,
        image: './images/innermirror.jpg'
      },
      {
        id: 4,
        name: '牙齿修复',
        price: 800,
        image: './images/innermirror.jpg'
      }
    ],
    allSelected: true,
    totalPrice: 0,
    discount: 100,
    selectedCount: 0
  },

  onLoad() {
    
    this.queryCartInfo();

  },

  queryCartInfo() {
    const userId = 1;

    // 第一步：查询 cart 表
    client.models.cart.list({
      filter: {
        where: {
          $and: [{
            userId: {
              $eq: 1
            }
          }]
        }
      },
      pageSize: 10,
      pageNumber: 1,
      getCount: true
    }).then((cartRes) => {
      const cartList = cartRes.data.records;
      const productIds = cartList.map((cart) => cart.productId);  // 提取商品Id

      // 第二步：查询 product_info 表
      client.models.product_info.list({
        filter: {
          where: {
            productId: {
              $in: productIds  // 批量查询商品
            }
          }
        }
      }).then((productRes) => {
        const productList = productRes.data.records;
        const productMap = {};  // 将分类信息转为 Map,方便查找
        productList.forEach((product) => {
          productMap[product.productId] = product;
        });

        // 第三步：将商品信息关联到购物车
        const result = cartList.map((cart) => {
          return {
            ...cart,
            productInfo: productMap[cart.productId]  // 关联商品信息
          };
        });

        this.showCartItem(result);

        const totalPriceVal = result.reduce((sum, cartItem) => sum + cartItem.productInfo.price, 0);

        this.setData({
          selectedCount: result.length,
          totalPrice: totalPriceVal
        });

        console.log("查询结果", result);

      }).catch((err) => {
        console.error('查询商品失败', err);
      });

      console.log('查询结果：', cartRes);
    }).catch((err) => {
      console.log('查询失败：', err);
    });

  },

  showCartItem(datas) {

    const cartItemDataset = datas.map((cartItem) => {
      return {
        id: cartItem.productId,
        name: cartItem.productInfo.productName,
        specification: cartItem.productInfo.description,
        price: cartItem.productInfo.price,
        quantity: cartItem.quantity,
        image: cartItem.productInfo.images.url,
        selected: true,
        cartId: cartItem._id
      };
    });

    this.setData({
      cartItems: cartItemDataset
    });
  },

  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const items = this.data.cartItems.map(item => {
      if (item.id === id) {
        return { ...item, selected: !item.selected };
      }
      return item;
    });
    this.setData({ cartItems: items });
    this.updateTotalPrice();
    this.updateSelectAll();
  },

  toggleSelectAll() {
    const allSelected = !this.data.allSelected;
    const items = this.data.cartItems.map(item => ({
      ...item,
      selected: allSelected
    }));
    this.setData({
      allSelected,
      cartItems: items
    });
    this.updateTotalPrice();
  },

  increaseQuantity(e) {
    const cartId = e.currentTarget.dataset.id;
    const items = this.data.cartItems.map(item => {
      if (item.cartId === cartId) {
        return { ...item, quantity: item.quantity + 1 };
      }
      return item;
    });
    this.setData({ cartItems: items });
    this.updateTotalPrice();
  },

  decreaseQuantity(e) {
    const cartId = e.currentTarget.dataset.id;
    const items = this.data.cartItems.map(item => {
      if (item.cartId === cartId && item.quantity > 1) {
        return { ...item, quantity: item.quantity - 1 };
      }
      return item;
    });
    this.setData({ cartItems: items });
    this.updateTotalPrice();
  },

  updateQuantity(e) {
    const cartId = e.currentTarget.dataset.id;
    const quantity = parseInt(e.detail.value) || 1;
    const items = this.data.cartItems.map(item => {
      if (item.cartId === cartId) {
        return { ...item, quantity };
      }
      return item;
    });
    this.setData({ cartItems: items });
    this.updateTotalPrice();
  },

  deleteItem(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          const items = this.data.cartItems.filter(item => item.id !== id);
          this.setData({ cartItems: items });
          this.updateTotalPrice();
          this.updateSelectAll();
        }
      }
    });
  },

  updateTotalPrice() {
    const total = this.data.cartItems.reduce((sum, item) => {
      if (item.selected) {
        return sum + item.price * item.quantity;
      }
      return sum;
    }, 0);
    const selectedCount = this.data.cartItems.filter(item => item.selected).length;
    this.setData({
      totalPrice: total,
      selectedCount
    });
  },

  updateSelectAll() {
    const allSelected = this.data.cartItems.length > 0 && 
      this.data.cartItems.every(item => item.selected);
    this.setData({ allSelected });
  },

  navigateToService() {
    wx.switchTab({
      url: '/pages/service/service'
    });
  },

  addToCart(e) {
    const id = e.currentTarget.dataset.id;
    // 添加到购物车的逻辑
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
  },

  queryProductDetail(e) {
    const id = e.currentTarget.dataset.id;

    wx.navigateTo({
      url: '/page/productdetail/index?param1=' + id,
    })
  },

  checkout() {
    if (this.data.selectedCount === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    // 结算逻辑
    wx.navigateTo({
      url: '/pages/checkout/index'
    });
  }
}); 